package com.fzebu.fastboot.util;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.*;

/**
 * @author Jack
 * @version 1.0.0
 * @create 2020/1/11 21:29
 */
public class BeanValidator {

    private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> Map<String, String> validate(T obj, Class<?>... groups) {
        Set<ConstraintViolation<T>> resultSet = VALIDATOR.validate(obj, groups);
        Map<String, String> map = new HashMap<>(resultSet.size());
        if (!resultSet.isEmpty()) {
            for (ConstraintViolation<T> violation : resultSet) {
                map.put(violation.getPropertyPath().toString(), violation.getMessage());
            }
        }
        return map;
    }

    public static Map<String, String> validate(Collection<?> collection) {
        Map<String, String> errors = new TreeMap<>();
        if (collection == null || collection.size() <= 0) {
            return errors;
        }
        int i = 0;
        for (Object obj : collection) {
            Map<String, String> map = validate(obj);
            if (!map.isEmpty()) {
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    errors.put("["+ i +"]." + entry.getKey(), entry.getValue());
                }
            }
            i ++;
        }
        return errors;
    }
}
